package 剑指offer;

/**
 * 把字符串转换成整数
 * https://leetcode-cn.com/problems/string-to-integer-atoi/solution/jin-liang-bu-shi-yong-ku-han-shu-nai-xin-diao-shi-/
 */
public class Offer67_JZ49 {
    public int strToInt(String str) {
        char[] chars = str.toCharArray();
        int len = chars.length;
        int index = 0;
        // 去除空格
        while (index<len && chars[index] == ' ') {
            index++;
        }
        if (index >= len) {
            return 0;
        }
        // 处理符号
        int sign = 1;
        if (chars[index] == '-') {
            sign = -1;
            index++;
        } else if (chars[index] == '+') {
            index++;
        }

        // 处理数字
        int res = 0, last = 0;
        while (index < len) {
            char char1 = chars[index];
            if (char1<'0' || char1>'9') {
                break;
            }
            int temp = char1 - '0';
            last = res;
            res = res * 10 + temp;
            if (last != (res/10)) {
                return sign==-1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            index++;
        }
        return res * sign;
    }

    public static void main(String[] args) {
        Offer67_JZ49 demo = new Offer67_JZ49();
        System.out.println(demo.strToInt("42"));
        System.out.println(demo.strToInt("   -42"));
        System.out.println(demo.strToInt("4193 with words"));
        System.out.println(demo.strToInt("words and 987"));
        System.out.println(demo.strToInt("-91283472332"));
        System.out.println(demo.strToInt("1a33"));
    }
}
